﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using blackhouse.IdentityCms.Business.Sites;
using blackhouse.IdentityCms.Data;

namespace blackhouse.IdentityCms.Business.Pages {
    public class CmsPages : ICollection<IPage> {

        #region Fields

        private readonly List<IPage> innerList;

        #endregion

        #region Properties

        public int Count {
            get { return this.innerList.Count; }
        }

        public bool IsReadOnly {
            get { return true; }
        }

        #endregion

        #region Constructors

        public CmsPages(int siteId) : this(siteId, GetSiteCulture(siteId)) { }

        public CmsPages(int siteId, CultureInfo culture) {
            IPageDbContext dbContext = DbFactory.GetPageDbContext();
            PageData[] pages = dbContext.GetPagesBySiteId(siteId, culture.Name);
            this.innerList = new List<IPage>(pages.Length);
            this.innerList.AddRange(pages.Select(pd => new CmsPage(pd)));
        }

        #endregion

        #region Methods

        private static CultureInfo GetSiteCulture(int siteId) {
            var siteLanguages = new CmsSiteLanguage(siteId);
            return siteLanguages.DefaultLanguage;
        }

        public void Add(IPage item) {
            throw new InvalidOperationException("Insert element to read only collection is not allowed");
        }

        public void Clear() {
            throw new InvalidOperationException("Clear read only collection is not allowed");
        }

        public bool Contains(IPage item) {
            return this.innerList.Contains(item);
        }

        public void CopyTo(IPage[] array, int arrayIndex) {
            this.innerList.CopyTo(array, arrayIndex);
        }

        public bool Remove(IPage item) {
            throw new InvalidOperationException("Remove element from read only collection is not allowed");
        }

        public IEnumerator<IPage> GetEnumerator() {
            return this.innerList.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return this.innerList.GetEnumerator();
        }

        #endregion

    }
}
